//
//  DataManager.m
//  HandheldHospital
//
//  Created by zhangchao on 16/2/26.
//  Copyright © 2016年 zhangchao. All rights reserved.
//

#import "DataManager.h"
#import "ZC_AsynchronousBlock.h"
#import "Hospital.h"
#import "Medical.h"
#import "Registering.h"


@implementation DataManager

+ (instancetype)defaultManager
{
    static DataManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[DataManager alloc] init];
        manager.myUser = [AVUser currentUser];
        manager.userType = [AVUser currentUser][@"userType"];
        //初始化医院医生数组
        manager.doctorArray = [NSMutableArray array];
        //初始化患者数组
        manager.managerArray = [NSMutableArray array];
        //初始化病历数组
        manager.medicalArray = [NSMutableArray array];
        //初始化挂号订单数组
        manager.registerArray = [NSMutableArray array];
        //初始化就诊人数组
        manager.dataArray = [NSMutableArray array];
        //初始化收藏的医生数组
        manager.collectDoctorArray = [NSMutableArray array];
        //初始化收藏的医院数组
        manager.collectHospitalArray = [NSMutableArray array];
        //初始化城市的医院数组
        manager.cityHospitalArray = [NSMutableArray array];
        if(manager.myUser != nil)
        {
            //获取医生信息
            [manager getSeekModel];
            //获取当前用户收藏的医院
            [manager getCollectHospitalArray];
            //获取当前用户收藏的医生
            [manager getCollectDoctorArray];
        }
        //获取所有医生
        [manager getSeekArray];
        //获取所有医院
        [manager getHospitalArray];
    });
    return manager;
}

//获取token
- (void)getTokenWithBlock:(STRBLOCK)block
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:[AVUser currentUser].username forKey:@"name"];
    [dic setValue:[AVUser currentUser].email forKey:@"userId"];
    //取得当前用户的头像信息
    AVFile *file = [AVUser currentUser][@"Picture"];
    [dic setValue:file.url forKey:@"portraitUri"];
    //获取body
    NSData *da = [ZC_AsynchronousBlock httpBodyFromParamDictionary:dic];
    
    [ZC_AsynchronousBlock asynchronousPOSTWithURLString:@"https://api.cn.ronghub.com/user/getToken.json" AppKey:@"uwd1c0sxdbad1" AppSecret:@"1ery3DRvC5k" body:da PassBlock:^(NSData *data) {
        if(data)
        {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            //取得当前token
            self.token = dict[@"token"];
            block(self.token);

        }
    }];
}

//获取所有医生
- (void)getSeekArray
{
    self.seekArray = [NSMutableArray array];
    AVQuery *query = [AVQuery queryWithClassName:@"SeekModel"];
    [query includeKey:@"currentUser"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        for(SeekModel *seek in objects)
        {
            [self.seekArray addObject:seek];
        }
    }];

}

//获取所有医生并通过BLOCK刷新表视图
- (void)getSeekArrayAndBlock:(BLOCK)block
{
    AVQuery *query = [AVQuery queryWithClassName:@"SeekModel"];
    [query includeKey:@"currentUser"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        self.seekArray = [NSMutableArray arrayWithArray:objects];
        dispatch_async(dispatch_get_main_queue(), ^{
            block();
        });
    }];

}

//获取所有医院
- (void)getHospitalArray
{
    AVQuery *query = [AVQuery queryWithClassName:@"Hospital"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        self.hospitalArray = [NSArray arrayWithArray:objects];
    }];
}

//获取所有医院并刷新表视图
- (void)getHospitalArrayAndBlock:(BLOCK)block
{
    AVQuery *query = [AVQuery queryWithClassName:@"Hospital"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        self.hospitalArray = [NSArray arrayWithArray:objects];
        dispatch_async(dispatch_get_main_queue(), ^{
            block();
        });
    }];
}


//获取医生信息
- (void)getSeekModel
{
    if([self.userType isEqualToString:@"医生"])
    {
        AVQuery *query = [AVQuery queryWithClassName:@"SeekModel"];
        [query whereKey:@"currentUser" equalTo:[AVUser currentUser]];
        [query includeKey:@"currentUser"];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            self.seek = [objects firstObject];
        }];
    }
}


//获取就诊人信息并刷新下拉视图
- (void)getDataArrayAndBlock:(BLOCK)block
{
    if(self.dataArray.count > 0)
    {
        [self.dataArray removeAllObjects];
    }
    if([self.userType isEqualToString:@"医生"])
    {
            [self getManagerArrayAndBlock:^{
                for(AVUser *user in self.managerArray)
                {
                    AVQuery *query = [AVQuery queryWithClassName:@"PatientData"];
                    [query whereKey:@"currentUser" equalTo:user];
                    [query includeKey:@"currentUser"];
                    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                        for(PatientData *patient in objects)
                        {
                            [self.dataArray addObject:patient];
                        }
                        dispatch_async(dispatch_get_main_queue(), ^{
                            block();
                        });
                    }];
                }
            }];
    }
    else
    {
        AVQuery *query = [AVQuery queryWithClassName:@"PatientData"];
        [query whereKey:@"currentUser" equalTo:self.myUser];
        [query includeKey:@"currentUser"];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            self.dataArray = [NSMutableArray arrayWithArray:objects];
            dispatch_async(dispatch_get_main_queue(), ^{
                block();
            });
        }];
    }
}

//通过医院名称得到医院的医生列表，并刷新列表
- (void)getDoctorArrayWithHospitalName:(NSString *)hospitalName AndBlock:(BLOCK)block
{
    AVQuery *query = [AVQuery queryWithClassName:@"SeekModel"];
    [query whereKey:@"yiyuan" containsString:hospitalName];
    [query includeKey:@"currentUser"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if(self.doctorArray.count > 0)
        {
            [self.doctorArray removeAllObjects];
        }
        for(SeekModel *seek in objects)
        {
            [self.doctorArray addObject:seek];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            block();
        });
    }];
}

//获取当前用户收藏的医院
- (void)getCollectHospitalArray
{
    AVQuery *query = [AVUser query];
    [query whereKey:@"username" equalTo:self.myUser.username];
    [query includeKey:@"collectHospital"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        NSArray *arr = [objects firstObject][@"collectHospital"];
        self.collectHospitalArray = [NSMutableArray arrayWithArray:arr];
    }];
}

//获取当前用户收藏的医生
- (void)getCollectDoctorArray
{
    AVQuery *query = [AVUser query];
    [query whereKey:@"username" equalTo:self.myUser.username];
    [query includeKey:@"collectDoctor"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if(self.collectDoctorArray.count > 0)
        {
            [self.collectDoctorArray removeAllObjects];
        }
        NSArray *arr = [objects firstObject][@"collectDoctor"];
        self.collectDoctorArray = [NSMutableArray arrayWithArray:arr];
    }];
}


//获取当前用户所有的患者
- (void)getManagerArrayAndBlock:(BLOCK)block
{
    AVQuery *query = [AVQuery queryWithClassName:@"ManagerArray"];
    [query whereKey:@"doctor" equalTo:self.myUser];
    [query includeKey:@"manager"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if(self.managerArray.count > 0)
        {
            [self.managerArray removeAllObjects];
        }
        for (AVObject *obj in objects) {
            [self.managerArray addObject:obj[@"manager"]];
        }
        block();
    }];
}

//获取就诊人的电子病历
- (void)getMedicalArrayWithPatient:(PatientData *)patient AndBlock:(BLOCK)block
{
    if(self.medicalArray.count > 0)
    {
        [self.medicalArray removeAllObjects];
    }
    AVQuery *query = [AVQuery queryWithClassName:@"Medical"];
    [query whereKey:@"patient" equalTo:patient];
    [query includeKey:@"patient"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        for(Medical *medical in objects)
        {
            [self.medicalArray addObject:medical];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            block();
        });
    }];
}

//获取当前用户挂号订单
- (void)getRegisterArrayAndBlock:(BLOCK)block
{
    if(self.registerArray.count > 0)
    {
        [self.registerArray removeAllObjects];
    }
    AVQuery *query = [AVQuery queryWithClassName:@"Registering"];
    [query whereKey:@"currentUser" equalTo:[AVUser currentUser]];
    [query includeKey:@"currentUser"];
    [query includeKey:@"patient"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
       for(Registering *registering in objects)
       {
           [self.registerArray addObject:registering];
       }
        block();
    }];
}

//通过传进来的省和市找到对应的医院数组
- (void)getCityHospitalArrayWithState:(NSString *)state City:(NSString *)city AndBlock:(BLOCK)block
{
    if(self.cityHospitalArray.count > 0)
    {
        [self.cityHospitalArray removeAllObjects];
    }
    AVQuery *query = [AVQuery queryWithClassName:@"Hospital"];
    [query whereKey:@"state" containsString:state];
    [query whereKey:@"city" containsString:city];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        for(Hospital *hospital in objects)
        {
            [self.cityHospitalArray addObject:hospital];
        }
        block();
    }];
}

@end
